package com.bbs.service;

import com.bbs.common.entity.User;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.UserMapper;
import com.bbs.common.utils.RequestContextUtils;
import com.bbs.dto.ProfileUpdateDTO;
import com.bbs.dto.UpdatePasswordDTO;
import com.bbs.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * UserService
 *
 * @author yangjiajia
 * @since 2024/5/9 17:29
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 修改个人信息
     **/
    public UserVo update(ProfileUpdateDTO updateDTO) {
        int userId = RequestContextUtils.getUserId();
        User user = userMapper.selectById(userId);
        if (null == user) {
            throw new CommonException("用户不存在");
        }

        BeanUtils.copyProperties(updateDTO, user);
        userMapper.updateById(user);

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    /**
     * 修改密码
     **/
    public void updatePwd(UpdatePasswordDTO updatePasswordDTO) {
        int userId = RequestContextUtils.getUserId();
        User user = userMapper.selectById(userId);
        if (null == user) {
            throw new CommonException("用户不存在");
        }

        if (!user.getPassword().equals(updatePasswordDTO.getPassword())) {
            throw new CommonException("原密码不正确");
        }

        user.setPassword(updatePasswordDTO.getNewPassword());
        userMapper.updateById(user);
    }
}
